package com.genexususa.eo.facebook.connection;

import com.genexususa.eo.facebook.data.FacebookPost;
import com.genexususa.eo.facebook.data.FacebookPosts;
import com.genexususa.eo.facebook.util.Constants;
import com.genexususa.eo.facebook.util.Info;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.json.JsonObject;
import com.restfb.types.Insight;
import com.restfb.types.Post;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

public class PostManager {

    public void getAllAccountsPostInsights(String startDate, String endDate, String locationFile, Long waitBetweenRequests){

        AccountManager am = new AccountManager();
        ArrayList<String> accounts = am.getAllAccounts();
        ArrayList<Thread> threads = new ArrayList<Thread>();
        for (String account : accounts){

            GetPosts getPosts = new GetPosts(account, startDate, endDate, locationFile);
            getPosts.start();
            threads.add(getPosts);

            try {
                Thread.sleep(waitBetweenRequests);
            }catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

        }

        for (Thread thread : threads){
            try{
                thread.join();
                //System.out.println(thread.getName() + " ended!");
            }catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

    }


    public void getPostInsights(String accountId, String startDate, String endDate, String locationFile){

        String result = "";

        FacebookPosts facebookPosts = new FacebookPosts();

        DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTime since = df.parseDateTime(startDate);
        DateTime until = df.parseDateTime(endDate);

        HashMap<String, String> info = null;
        try {
            info = Info.getFacebookProperties();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String accessToken = info.get(Constants.ACCESS_TOKEN);

        FacebookClient client = new DefaultFacebookClient(accessToken);

        Connection<Post> posts = client.fetchConnection(accountId + "/posts",
                Post.class, Parameter.with("limit", 250),
                Parameter.with("since", since.getMillis() / 1000L),
                Parameter.with("until", until.getMillis() / 1000L));


        for (Post post : posts.getData()){

            FacebookPost facebookPost = new FacebookPost();

            facebookPost.Id = post.getId();
            //facebookPost.Clicks = post.get
            facebookPost.Message = post.getMessage();
            facebookPost.Link = post.getLink();
            facebookPost.Type = post.getType();
            facebookPost.Likes = 0L;
            if (post.getLikes() != null){
                if (post.getLikes().getData() != null)
                    facebookPost.Likes = Long.valueOf(post.getLikes().getData().size());
            }

            DateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            facebookPost.Date = dtf.format(post.getCreatedTime());

            Connection<Insight> postInsights = client.fetchConnection(post.getId() + "/insights", Insight.class);

            for (Insight insight : postInsights.getData()) {

                if (insight.getDescription().equalsIgnoreCase(Constants.TOTAL_REACH)){
                    for (JsonObject value : insight.getValues()){
                        facebookPost.Reach = value.getLong("value");
                    }
                }

                if (insight.getDescription().equalsIgnoreCase(Constants.TOTAL_CLICKS)){
                   for (JsonObject value : insight.getValues()){
                        facebookPost.Clicks= value.getLong("value");
                   }
                }
            }


            facebookPosts.Posts.add(facebookPost);


        }


         try {

            JAXBContext contextObj = JAXBContext.newInstance(FacebookPosts.class);

            Marshaller marshallerObj = contextObj.createMarshaller();
            marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();

            marshallerObj.marshal(facebookPosts, sw);
            result = sw.getBuffer().toString();
            System.out.println(result);
            String s = "";

            FileWriter fw = new FileWriter(locationFile + File.separator + "PostInsights-" + accountId + ".xml");
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(result);
            bw.flush();
            bw.close();


        } catch (Exception excAux) {

        }


    }
}

class GetPosts extends Thread{

    private String accountId;
    private String startDate;
    private String endDate;
    private String locationFile;

    public GetPosts(String accountId, String startDate, String endDate, String locationFile){
        this.accountId = accountId;
        this.startDate = startDate;
        this.endDate = endDate;
        this.locationFile = locationFile;
    }

    public void run(){
        PostManager pm = new PostManager();
        pm.getPostInsights(accountId, startDate, endDate, locationFile);
    }

}
